// 登录API函数
export const login = async (username, password) => {
  try {
    const response = await fetch('http://127.0.0.1:5000/api/login', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ username, password }),
    });
    const data = await response.json();
    if (!response.ok) {
      throw new Error('Invalid credentials');
    }
    // 存储JWT令牌
    if (data.access_token) {
      localStorage.setItem('token', data.access_token);
    }
    return data;
  } catch (error) {
    console.error('登录错误:', error);
    throw error; // 重新抛出错误，让调用者能够捕获
  }
};

// 注册API函数
export const register = async (username, password, userType, teacherInfo = {}) => {
  try {
    const response = await fetch('http://localhost:5000/api/register', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        username,
        password,
        user_type: userType,
        ...(userType === 'teacher' && teacherInfo)
      }),
    });
    const data = await response.json();
    if (!response.ok) {
      throw new Error(data.message || '注册失败');
    }
    return data;
  } catch (error) {
    console.error('注册错误:', error);
    throw error;
  }
};